package edu.fiu.cis.personalize.server.berkDB.serializers;

import java.util.Map;
import java.util.Map.Entry;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

public abstract class MapSerializer<K, V> extends TupleBinding<Map<K, V>> {

	@Override
	public Map<K, V> entryToObject(TupleInput ti) {
		int size = ti.readInt();
		Map<K, V> m = createInstance();
		for (int i = 0; i < size; i++) {
			m.put(readKey(ti), readValue(ti));
		}
		return m;
	}

	protected abstract Map<K, V> createInstance();

	protected abstract K readKey(TupleInput ti);

	protected abstract V readValue(TupleInput ti);

	protected abstract void writeKey(TupleOutput to, K key);

	protected abstract void writeValue(TupleOutput to, V value);

	@Override
	public void objectToEntry(Map<K, V> m, TupleOutput to) {
		to.writeInt(m.entrySet().size());
		for (Entry<K, V> e : m.entrySet()) {
			writeKey(to, e.getKey());
			writeValue(to, e.getValue());
		}

	}

}
